<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Console extends Base {
	// construct
	public function run() {
		// set permissions
		$this->permissions();

		// manage uri paths
		if(count($this->uri) > 0) {
			@list($func) = $this->uri;
			$this->$func();
		} else $this->index();
	}

	// permissions
	private function permissions() {
		// not logged in? don't bother
		if(!isset($this->session->auth))
			die(new Error());

		// no root access?
		if(!(isset($this->session->auth['permissions']['root']) && $this->session->auth['permissions']['root'] == 1))
			die(new Error());
	}

	// show all ranks
	public function index() {
		$this->view->func = 'index';
		$this->view->php_to_js = json_encode(array(
			'year' => date('Y'),
			'guild' => $this->settings['blizz_guild']
		));

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// show all variables
	public function settings() {
		return $this->json = array('success' => true, 'settings' => $this->settings);
	}

	// get a variable
	public function get() {
		// get vars
		$cmd = $this->request->post('cmd', 'array');
		if(is_null($cmd))
			return $this->json = array('success' => false);

		// get key
		$key = @trim($cmd[1]);

		// no valid key?
		if(!isset($this->settings[$key]))
			return $this->json = array('success' => false);

		// return variable
		return $this->json = array('success' => true, 'value' => $this->settings[$key]);
	}

	// set a variable
	public function set() {
		// get vars
		$cmd = $this->request->post('cmd', 'array');
		if(is_null($cmd))
			return $this->json = array('success' => false);

		// get key and value
		$key = @trim($cmd[1]);
		unset($cmd[0], $cmd[1]);
		$value = @trim(implode(' ', $cmd));

		// no key?
		if(!strlen($key) > 0)
			return $this->json = array('success' => false);

		// no valid key?
		if(!isset($this->settings[$key]))
			return $this->json = array('success' => false);

		// no value?
		if(!strlen($value) > 0)
			return $this->json = array('success' => false, 'value' => true);

		// prepare vars
		$key = $this->db->escapeString($key);
		$value = $this->db->escapeString($value);

		// run query
		$this->db->exec("UPDATE settings SET value = '{$value}' WHERE key = '{$key}'");

		// return variable
		return $this->json = array('success' => true, 'value' => $value);
	}

	// save a backup
	public function backup() {
		// get vars
		$cmd = $this->request->post('cmd', 'array');
		if(is_null($cmd))
			return $this->json = array('success' => false);

		// get key and value
		$key = @trim($cmd[1]);
		unset($cmd[0], $cmd[1]);
		$value = @trim(implode(' ', $cmd));

		// no key? display all backups then
		if(!strlen($key) > 0) {
			$backups = array();
			if($handle = opendir(ROOT . DS . 'db')) {
				while(false !== ($entry = readdir($handle)))
					if ($entry != "." && $entry != ".." && $entry != "app.db")
			            $backups[preg_replace('/\.[^.]+$/','', $entry)] = date("Y-m-d H:i:s", filectime(ROOT . DS . 'db' . DS . $entry));

			    closedir($handle);
			}

			// no backups?
			if(!count($backups) > 0)
				return $this->json = array('success' => false, 'msg' => 'No backups available...{br}Manage backups by using these commands: `save`, `restore`, `delete`.');

			return $this->json = array('success' => true, 'backups' => $backups);
		}

		// switch on commands
		switch($key) {
			case 'save':
				// no valid value?
				if(!strlen($value) > 0)
					return $this->json = array('success' => false, 'msg' => 'Backup name is empty. Correct syntax is `backup save name`.');

				// name is app? invalid
				if($value == 'app')
					return $this->json = array('success' => false, 'msg' => 'Backup name `app` is invalid. Please select a different name.');

				// backup already exists?
				if(@file_exists(ROOT . DS . 'db' . DS . $value . '.db'))
					return $this->json = array('success' => false, 'msg' => 'Backup name `'. $value .'` already exists. Please select a different name.');

				// try to create the backup
				if(!@copy(ROOT . DS . 'db' . DS . 'app.db', ROOT . DS . 'db' . DS . $value . '.db'))
				    return $this->json = array('success' => false, 'msg' => 'Backup creation failed. Make sure we have a 777 chmod on `db`.');

				// done
				return $this->json = array('success' => true, 'msg' => 'Backup `' . $value . '` saved.');
			break;

			case 'restore':
				// no valid value?
				if(!strlen($value) > 0)
					return $this->json = array('success' => false, 'msg' => 'Backup name is empty. Correct syntax is `backup restore name`.');

				// name is app? invalid
				if($value == 'app')
					return $this->json = array('success' => false, 'msg' => 'Backup name `app` was not found. Please select a different name.');

				// backup doesnt exists?
				if(!@file_exists(ROOT . DS . 'db' . DS . $value . '.db'))
					return $this->json = array('success' => false, 'msg' => 'Backup name `'. $value .'` was not found. Please select a different name.');

				// try to restore the backup
				$this->db->close(); // TODO: may not be enough if the socket.io server is running
				if(!@rename(ROOT . DS . 'db' . DS . $value . '.db', ROOT . DS . 'db' . DS . 'app.db'))
				    return $this->json = array('success' => false, 'msg' => 'Backup restoration failed. Make sure we have a 777 chmod on `db`.');

				// done
				return $this->json = array('success' => true, 'msg' => 'Backup `' . $value . '` restored.');
			break;

			case 'delete':
				// no valid value?
				if(!strlen($value) > 0)
					return $this->json = array('success' => false, 'msg' => 'Backup name is empty. Correct syntax is `backup delete name`.');

				// name is app? invalid
				if($value == 'app')
					return $this->json = array('success' => false, 'msg' => 'Backup name `app` was not found. Please select a different name.');

				// backup doesnt exists?
				if(!@file_exists(ROOT . DS . 'db' . DS . $value . '.db'))
					return $this->json = array('success' => false, 'msg' => 'Backup name `'. $value .'` was not found. Please select a different name.');

				// try to delete the backup
				if(!@unlink(ROOT . DS . 'db' . DS . $value . '.db'))
				    return $this->json = array('success' => false, 'msg' => 'Backup deletion failed. Make sure we have a 777 chmod on `db`.');

				// done
				return $this->json = array('success' => true, 'msg' => 'Backup `' . $value . '` deleted.');
			break;

			default:
				return $this->json = array('success' => false, 'msg' => 'Command `' . $key . '` doesn\'t exist. Commands are `save`, `restore`, `delete`.');
			break;
		}
	}
}